<?php


namespace backend\modules\media\controllers;

use Yii;
use yii\web\Controller;
use yii\web\UploadedFile;
use yii\helpers\FileHelper;
use yii\helpers\StringHelper;
use backend\models\UploadForm;
use common\components\Helper;

/**
 * description of ImagesController
 *
 * @author FireLoong
 */
class ImagesController extends Controller
{
    public function actionIndex()
    {
        $get = Yii::$app->request->get();
        $get['folder'] = $get['folder'] ?? '';

        $mediaRootPath = Yii::getAlias($this->module->mediaPath);
        $allFolders = FileHelper::findDirectories($mediaRootPath);
        foreach ($allFolders as $key => $item) {
            $item = substr($item, strlen($mediaRootPath));
            unset($allFolders[$key]);
            $allFolders[trim($item, '/')] = $item;
        }
        $allFolders = array_merge(['' => '/'], $allFolders);

        $mediaCurrentPath = Yii::getAlias(trim($this->module->mediaPath, '/') . '/' . trim($get['folder']));
        $folders = FileHelper::findDirectories($mediaCurrentPath, ['recursive' => false]);
        $images = FileHelper::findFiles($mediaCurrentPath, ['recursive' => false, 'filter' => function ($item) {
            if (is_file($item)) {
                $mimeTypeByExt = StringHelper::startsWith(FileHelper::getMimeTypeByExtension($item), 'image/');
                $mimeType = StringHelper::startsWith(FileHelper::getMimeType($item), 'image/');
                return $mimeTypeByExt && $mimeType;
            } else {
                return false;
            }
        }]);

        $upload = new UploadForm(['exts' => 'jpg, jpeg, png, gif, bmp, svg']);

        return $this->renderPartial('index', [
            'allFolders' => $allFolders,// 所有文件夹
            'get' => $get,// 当前文件夹
            'media' => array_merge($folders, $images),
            'mediaRootPath' => $mediaRootPath,
            'upload' => $upload
        ]);
    }

    /**
     * 上传图片
     */
    public function actionUpload()
    {
        $folder = Yii::$app->request->get('folder');
        $upload = new UploadForm(['exts' => 'jpg, jpeg, png, gif, bmp, svg']);
        $upload->file = UploadedFile::getInstance($upload, 'file');
        if ($upload->upload($this->module->mediaPath . ($folder ? '/' . $folder : ''))) {
            Yii::$app->session->addFlash('success', Yii::t('mod_media', 'UPLOAD_SUCCESS', $upload->file->name));
        } else {
            Yii::$app->session->addFlash('error', Helper::errorsToString($upload->errors));
        }
        $url = $folder ? ['index', 'folder' => $folder] : ['index'];
        $this->redirect($url);
    }
}
